package itsm.isperp.module.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IRole;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.module.dto.project.ProjectDomain;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.Collection;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;

/**
 *
 *
 * 项目与控制器
 *
 * @author lizx
 * @date 2013-9-28
 * @since 1.0
 *
 */
public final class ProjectDomainUtils {

  private static final String PROJECT_DOMATIN = "SELECT proj_project_id FROM proj_project_member a LEFT JOIN v_app_user_role b ON  a.app_user_name = b.app_user_name WHERE a.app_user_name='%s' AND  b.data_range >='%s' ";

  // /**
  // *
  // * @return
  // */
  // public static final String getUserDomainSql() {
  //
  // return String.format(RECEIPT_PROJECT_DOMATIN,
  // ContextHolder.getLoginUsername());
  // }

  // 此处可以通过缓存优化

  public static final int getUserMaxDataRange() {
    IUser user = ContextHolder.getLoginUser();
    Collection<? extends GrantedAuthority> roles = user.getAuthorities();
    // 如果用户具有公司级数据权限，则不需要对数据进行过滤
    int maxDataRange = 11;
    for (GrantedAuthority g : roles) {
      IRole r = (IRole) g;
      if (r.getDataRange() > maxDataRange) {
        maxDataRange = r.getDataRange();
      }
    }
    return maxDataRange;
  }
  public static final int getUserMaxDataRange(IUser user) {
    Collection<? extends GrantedAuthority> roles = user.getAuthorities();
    // 如果用户具有公司级数据权限，则不需要对数据进行过滤
    int maxDataRange = 11;
    for (GrantedAuthority g : roles) {
      IRole r = (IRole) g;
      if (r.getDataRange() > maxDataRange) {
        maxDataRange = r.getDataRange();
      }
    }
    return maxDataRange;
  }


  public static final String getUserDomainSqlForWechat(String userName,String projectIdName)
  {
    int maxDataRange = 11;
    String sql="SELECT MAX(data_range) r FROM `v_app_user_role` WHERE app_user_name='"+userName+"'";
    JdbcTemplate jdbcTemplate = ContextHolder
            .getSpringBean("jdbcTemplate");
    Integer tr=jdbcTemplate.queryForObject(sql, Integer.class);
    if(tr!=null)
      maxDataRange=tr;
    switch (maxDataRange) {
      case 1111: // 如果用户具有公司级数据权限，则不需要对数据进行过滤
        return "";
      case 111: // 如果用户具有项目级权限，则用户只能看到关联项目中的数据 或者他创建的工单

        // 1、要获取这个人所在的项目及其角色
        // 2、根据每一个项目角色，获取其具有的数据权限

        StringBuilder sb = new StringBuilder();
        sb.append(" AND ( "+projectIdName+" IN(");

        sb.append(String.format(PROJECT_DOMATIN,
                userName, 111));
        sb.append(") or (creator='" + userName + "'))");

        return sb.toString();

      case 11: // 如果用户具有工单级权限，则用户只能查看他创建的工单
        return " AND ("
                + BpmConst.getQueryMyAllRelateTaskSqlCondition("%",
                userName) + ")";
      case 22:
        AppUserService appUserService = ContextHolder
                .getSpringBean("appUserService");
        Map<String, Object> tUser = appUserService.findOneDetailByUsername(userName);
        String treeNodePath = tUser.get("department_treenode_path").toString();
        return " AND EXISTS(SELECT 1 FROM app_user c LEFT JOIN app_department d ON c.app_department_id=d.id WHERE c.id=cus_user_id AND d.treenode_path LIKE '%"
                + treeNodePath + "%' )";
      case 33:
        return " and project_id in(SELECT id FROM proj_project WHERE cus_customer_id IN(SELECT customer_id FROM app_user WHERE NAME='"+userName+"'))";
    }
    return null;
  }

  /**
   * 人员数据权限sql
   *
   * @param projectDomain
   * @return
   */
  public static final String getUserDomainSql(ProjectDomain projectDomain) {
    IUser user = ContextHolder.getLoginUser();

    // 逻辑调整
    Collection<? extends GrantedAuthority> roles = user.getAuthorities();
    // 如果用户具有公司级数据权限，则不需要对数据进行过滤
    int maxDataRange = 11;
    for (GrantedAuthority g : roles) {
      IRole r = (IRole) g;
      if (r.getDataRange() > maxDataRange) {
        maxDataRange = r.getDataRange();
      }
      // if (r.getDataRange() == 1111) {
      // return "";
      // }
    }

    switch (maxDataRange) {
      case 1111: // 如果用户具有公司级数据权限，则不需要对数据进行过滤
        return "";
      case 111: // 如果用户具有项目级权限，则用户只能看到关联项目中的数据 或者他创建的工单

        // 1、要获取这个人所在的项目及其角色
        // 2、根据每一个项目角色，获取其具有的数据权限

        StringBuilder sb = new StringBuilder();
        sb.append(" AND ( ").append(projectDomain.getColumn()).append(" IN(");

        sb.append(String.format(PROJECT_DOMATIN,
                ContextHolder.getLoginUsername(), 111));
        sb.append(") or (creator='" + ContextHolder.getLoginUsername() + "'))");

        return sb.toString();

      case 11: // 如果用户具有工单级权限，则用户只能查看他创建的工单
      /*
       * return " AND (" + BpmConst.getQueryMyTaskAttendSqlCondition("%",
       * ContextHolder.getLoginUsername()) + " OR " +
       * BpmConst.getQueryMyTaskStartedSqlCondition("%") + ")";
       */
        return " AND ("
                + BpmConst.getQueryMyAllRelateTaskSqlCondition("%",
                ContextHolder.getLoginUsername()) + ")";
      case 22:
        AppUserService appUserService = ContextHolder
                .getSpringBean("appUserService");
        Map<String, Object> tUser = appUserService.findOneDetailByUsername(user
                .getUsername());
        String treeNodePath = tUser.get("department_treenode_path").toString();
        return " AND EXISTS(SELECT 1 FROM app_user c LEFT JOIN app_department d ON c.app_department_id=d.id WHERE c.id=cus_user_id AND d.treenode_path LIKE '%"
                + treeNodePath + "%' )";
      case 33:
        return " and project_id in(SELECT id FROM proj_project WHERE cus_customer_id IN(SELECT customer_id FROM app_user WHERE NAME='"+user.getUsername()+"'))";
    }
    return null;

  }
}
